package cn.kgc.mes.workorder.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.kgc.mes.storage.domain.RtIssueLine;
import cn.kgc.mes.workorder.domain.ProWorkorder;
import cn.kgc.mes.workorder.domain.ProWorkorderBom;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.kgc.mes.common.annotation.Log;
import cn.kgc.mes.common.core.controller.BaseController;
import cn.kgc.mes.common.core.domain.AjaxResult;
import cn.kgc.mes.common.enums.BusinessType;
import cn.kgc.mes.workorder.domain.Task;
import cn.kgc.mes.workorder.service.ITaskService;
import cn.kgc.mes.common.utils.poi.ExcelUtil;
import cn.kgc.mes.common.core.page.TableDataInfo;

/**
 * 生产任务Controller
 * 
 * @author ydw
 * @date 2025-09-17
 */
@RestController
@RequestMapping("/task/task")
public class TaskController extends BaseController
{
    @Autowired
    private ITaskService taskService;

    /**
     * 查询生产任务列表
     */
//    @PreAuthorize("@ss.hasPermi('task:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(Task task)
    {
        startPage();
        List<Task> list = taskService.selectTaskList(task);
        return getDataTable(list);
    }
    //    根据workorderId查询
    @GetMapping("list1")
    public Object list1(@RequestParam("workorderId") Long workorderId){
        List<Task> list = taskService.selectTaskListByWorkorderId(workorderId);
        Map<String,Object> map=new HashMap<>();
        if(list!=null){
            map.put("code",200);
            map.put("msg","查询成功");
            map.put("data",list);
        }else{
            map.put("code",0);
            map.put("msg","查询失败");
        }
        return map;
    }


    //    根据workorderId查询已经排产的任务和未完成的任务（排产数量！=报工数量）
    @GetMapping("list2")
    public Object list2(@RequestParam("workorderId") Long workorderId){
        List<Task> list = taskService.selectTaskListByWorkorderId2(workorderId);
        Map<String,Object> map=new HashMap<>();
        if(list!=null){
            map.put("code",200);
            map.put("msg","查询成功");
            map.put("data",list);
        }else{
            map.put("code",0);
            map.put("msg","查询失败");
        }
        return map;
    }
    /**
     * 导出生产任务列表
     */
//    @PreAuthorize("@ss.hasPermi('task:task:export')")
    @Log(title = "生产任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Task task)
    {
        List<Task> list = taskService.selectTaskList(task);
        ExcelUtil<Task> util = new ExcelUtil<Task>(Task.class);
        util.exportExcel(response, list, "生产任务数据");
    }

    /**
     * 获取生产任务详细信息
     */
//    @PreAuthorize("@ss.hasPermi('task:task:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId)
    {
        return success(taskService.selectTaskByTaskId(taskId));
    }

    /**
     * 新增生产任务
     */
//    @PreAuthorize("@ss.hasPermi('task:task:add')")
    @Log(title = "生产任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Task task)
    {
        return toAjax(taskService.insertTask(task));
    }

    /**
     * 修改生产任务
     */
//    @PreAuthorize("@ss.hasPermi('task:task:edit')")
    @Log(title = "生产任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Task task)
    {
        return toAjax(taskService.updateTask(task));
    }

    /**
     * 删除生产任务
     */
//    @PreAuthorize("@ss.hasPermi('task:task:remove')")
    @Log(title = "生产任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable Long[] taskIds)
    {
        return toAjax(taskService.deleteTaskByTaskIds(taskIds));
    }

    @PostMapping("/addTask")
    public AjaxResult addTask(@RequestBody List<Task> list){
        System.out.println( list);
        for(Task task:list){
//            task.setStartTime1(null);
//            task.setEndTime(null);
            task.setDuration(null);
            task.setQuantity(BigDecimal.valueOf(0));
            task.setStatus("N");
        }
        boolean result = taskService.saveBatch(list);
        return toAjax(result);
    }



    /**
     *  获取近一周的每天的日期和任务数
     */
    @GetMapping("/TaskWeekAndNum")
    public TableDataInfo TaskWeekAndNum() {
        List<Task> list = taskService.selectTaskWeekAndNum();
        return getDataTable(list);
    }
    /**
     *  获取最近一天的未完成的任务数
     */
    @GetMapping("/TaskNumDay")
    public AjaxResult getRecentUnfinishedTasks() { // 方法名建议规范（首字母小写，见名知意）
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        // 1. 条件：状态不等于“已完成”（未完成任务）
        queryWrapper.ne(Task::getStatus, "已完成");
        // 2. 条件：创建时间在最近1天内
        LocalDateTime oneDayAgo = LocalDateTime.now().minus(1, ChronoUnit.DAYS);
        queryWrapper.ge(Task::getCreateTime, oneDayAgo);
        // 3. 查询任务列表
        List<Task> taskList = taskService.list(queryWrapper);
        // 4. 用AjaxResult包装返回（核心：符合若依规范）
        return AjaxResult.success(taskList);
        // 若需要自定义消息，可传第二个参数：AjaxResult.success("查询近1天未完成任务成功", taskList)
    }
    //获取当天结束的任务数
//    @GetMapping("/nowTask")
//    public AjaxResult getNowTask() {
//        LocalDateTime now = LocalDateTime.now();
//        LocalDateTime endOfDay = now.with(LocalTime.MIN);
//        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Task::getEndTime, endOfDay);
//        List<Task> taskList = taskService.list(queryWrapper);
//        return AjaxResult.success(taskList);
//    }
    @GetMapping("/nowTask")
    public AjaxResult getNowTask() {
        LocalDateTime now = LocalDateTime.now();
        // 获取当天的起始时间（00:00:00）
        LocalDateTime startOfDay = now.with(LocalTime.MIN);
        // 获取当天的结束时间（23:59:59.999999999）
        LocalDateTime endOfDay = now.with(LocalTime.MAX);
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        // 查询endTime在当天起始时间到当天结束时间之间的任务
        queryWrapper.between(Task::getEndTime, startOfDay, endOfDay);
        List<Task> taskList = taskService.list(queryWrapper);
        return AjaxResult.success(taskList);
    }
}
